#!/usr/bin/env node

/**
 * 调试网络接口信息
 * 查看所有可用的网络接口和IP地址
 */

const os = require('os');

console.log('🔍 调试网络接口信息');
console.log('==================');

const interfaces = os.networkInterfaces();
console.log('📊 原始网络接口数据:', JSON.stringify(interfaces, null, 2));

console.log('\n📡 所有网络接口:');
console.log('================');

Object.keys(interfaces).forEach(name => {
  console.log(`\n🔌 接口: ${name}`);
  const iface = interfaces[name];
  
  iface.forEach(addr => {
    const type = addr.internal ? '🏠 内部' : '🌐 外部';
    const family = addr.family === 'IPv4' ? 'IPv4' : 'IPv6';
    
    console.log(`  ${type} ${family}: ${addr.address}`);
    console.log(`    子网掩码: ${addr.netmask}`);
    console.log(`    MAC地址: ${addr.mac}`);
  });
});

console.log('\n🎯 当前IP检测逻辑结果:');
console.log('=====================');

// 复制getNetworkIP函数的逻辑
const ips = [];

Object.keys(interfaces).forEach(name => {
  const iface = interfaces[name];
  
  iface.forEach(addr => {
    if (addr.family === 'IPv4' && !addr.internal) {
      ips.push({
        interface: name,
        ip: addr.address,
        netmask: addr.netmask,
        mac: addr.mac
      });
    }
  });
});

console.log('\n📋 检测到的外部IPv4地址:');
ips.forEach((ip, index) => {
  console.log(`${index + 1}. 接口: ${ip.interface}`);
  console.log(`   IP: ${ip.ip}`);
  console.log(`   子网掩码: ${ip.netmask}`);
  console.log(`   MAC: ${ip.mac}`);
});

// 优先选择常见的局域网网段
const preferredRanges = [
  '192.168.',    // 家庭/办公室网络
  '10.',         // 企业网络
  '172.16.',     // 企业网络
  '172.17.',
  '172.18.',
  '172.19.',
  '172.20.',
  '172.21.',
  '172.22.',
  '172.23.',
  '172.24.',
  '172.25.',
  '172.26.',
  '172.27.',
  '172.28.',
  '172.29.',
  '172.30.',
  '172.31.'
];

// 按优先级排序
ips.sort((a, b) => {
  const aIndex = preferredRanges.findIndex(range => a.ip.startsWith(range));
  const bIndex = preferredRanges.findIndex(range => b.ip.startsWith(range));
  
  if (aIndex !== -1 && bIndex !== -1) {
    return aIndex - bIndex;
  }
  
  if (aIndex !== -1) return -1;
  if (bIndex !== -1) return 1;
  
  return a.ip.localeCompare(b.ip);
});

console.log('\n🏆 排序后的IP地址:');
ips.forEach((ip, index) => {
  const range = preferredRanges.find(r => ip.ip.startsWith(r));
  const priority = range ? `优先级: ${preferredRanges.indexOf(range) + 1}` : '优先级: 低';
  console.log(`${index + 1}. ${ip.ip} (${ip.interface}) - ${priority}`);
});

const selectedIP = ips.length > 0 ? ips[0].ip : '127.0.0.1';
console.log(`\n✅ 最终选择的IP: ${selectedIP}`);

console.log('\n💡 建议:');
console.log('========');
if (selectedIP !== '192.168.174.112') {
  console.log('❌ 检测到的IP与你的实际IP不匹配！');
  console.log('🔧 可能需要调整IP选择逻辑或手动指定IP');
} else {
  console.log('✅ IP检测正确！');
}
